/*
 * Copyright 2010 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jamwiki.servlets;

import org.jamwiki.utils.LinkUtil;
import org.jamwiki.utils.WikiLink;
import org.lightframework.jamwiki.EnvironmentEx;
import org.lightframework.jamwiki.RuntimeWikiException;
import org.lightframework.jamwiki.model.VirtualWiki;
import org.lightframework.jamwiki.servlets.WikiContext;

/**
 * @author fenghm(live.fenghm@gmail.com)
 */
public final class LinkUtilEx {

	/**
	 * gave the topic value 'Welcome' will return /{webappcontext}/special/Welcome 
	 */
	public static String buildSpecialTopicUrl(String topic){
		return WikiContext.contextPath() +  "/" + VirtualWiki.SPECIAL_WIKI_NAME + "/" + topic;
	}
	
	public static String buildTopicUrl(String topic){
		return WikiContext.contextPath() + "/" + WikiContext.wikiName() + "/" + topic;
	}
	
	public static String buildTopicEditUrl(String topic){
        return buildTopicEditUrl(WikiContext.wikiName(),topic);
	}
	
	public static String buildTopicEditUrl(String wiki,String topic){
        return buildTopicEditUrl(wiki,topic,false);
	}	
	
	public static String buildTopicEditUrl(String wiki,String topic,boolean returnto) {
		WikiLink link = new WikiLink();
		link.setDestination("Special:Edit");
		link.setQuery(LinkUtil.appendQueryParam("", "topic", topic));
		
		try {
	        if(returnto){
	        	String returnUrl = WikiContext.request().getRequestURI();
	        	if(null != WikiContext.request().getQueryString()){
	        		returnUrl = returnUrl + "?" + WikiContext.request().getQueryString();
	        	}
	        	//returnUrl = URLEncoder.encode(returnUrl,EnvironmentEx.PROP_PAGE_ENCODING.value);
	        	link.setQuery(LinkUtil.appendQueryParam(link.getQuery(), EnvironmentEx.CONST_RETURN_TO,returnUrl));
	        }
	        
	        return LinkUtil.buildTopicUrl(WikiContext.contextPath(), wiki, link);
        } catch (Exception e) {
        	throw new RuntimeWikiException(e);
        }
	}	

	/**
	 * gave the path value '/images/hello.png' will return '/{webappcontext}/images/hello.png';
	 */
	public static String asContextPath(String path){
		if(!path.startsWith("/")){
			path = "/" + path;
		}
		return WikiContext.contextPath() + path;
	}
}
